﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using Microsoft.VisualBasic;
using System.Data;
using AteckCsharp.Classes;
using System.Globalization;
using System.Web.Security;
namespace AteckCsharp
{
    public partial class _Default : System.Web.UI.Page
    {
        

        private ArrayList GetPreviousDates(int[] nDays, DayOfWeek today)
        {
            ArrayList days = new ArrayList();
            for (int i = 0; i < nDays.Length; i++)
            {
                int find = nDays[i];
                int delta = find - (int)today;
                if (delta > 0)
                {
                    days.Add(DateTime.Now.AddDays(delta));
                }
                else
                {
                    days.Add(DateTime.Now.AddDays(7 - delta));
                }
            }
            return days;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //  FirstDateOfWeek(2014, 52, CalendarWeekRule.FirstFullWeek);
            if (! IsPostBack)
            {
                String userId = Membership.GetUser(Session["User"].ToString()).ProviderUserKey.ToString();
                int weekNo;
                weekNo = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFullWeek, DayOfWeek.Saturday);
                DataSet ds = new DataSet();
                LoadDefaulPage loadDefault = new LoadDefaulPage(userId, weekNo.ToString());
              ds =  loadDefault.LoadWeek();
               
                gdvTimeBooking.DataSource = ds.Tables[0];
                gdvTimeBooking.DataBind();
                gdvTimeBooking.HeaderRow.Cells[1].Text = ds.Tables[1].Columns[0].ToString();
                gdvTimeBooking.HeaderRow.Cells[2].Text = ds.Tables[1].Columns[1].ToString();
                gdvTimeBooking.HeaderRow.Cells[3].Text = ds.Tables[1].Columns[2].ToString();
                gdvTimeBooking.HeaderRow.Cells[4].Text = ds.Tables[1].Columns[3].ToString();
                gdvTimeBooking.HeaderRow.Cells[5].Text = ds.Tables[1].Columns[4].ToString();
                gdvTimeBooking.HeaderRow.Cells[6].Text = ds.Tables[1].Columns[5].ToString();
                gdvTimeBooking.HeaderRow.Cells[7].Text = ds.Tables[1].Columns[6].ToString();
                if (DBNull.Value.Equals(ds.Tables[0].Rows[0][0]))
                {
                    btnSubmit.Text = "Submit";
                }
                else
                {
                    btnSubmit.Text = "Update";
                }
               
             }
      
        }
      
        protected void gdvTimeBooking_RowDataBound(object sender, GridViewRowEventArgs e)
        {
           
           if (e.Row.RowType == DataControlRowType.DataRow)
            {
               DropDownList projects;
               projects = (DropDownList)e.Row.FindControl("ddlProject");
               //projects.Items.Insert(0, "....Select....");
               projects.SelectedValue = gdvTimeBooking.DataKeys[e.Row.RowIndex].Values["ProjectId"].ToString();
                TextBox txtWed, txtMon, txtTue, txtSat, txtSun, txtThur, txtFri, total, totalAll, all;
                total = (TextBox)e.Row.FindControl("txtTotal");
                txtMon = (TextBox)e.Row.FindControl("txtMon");
                txtWed = (TextBox)e.Row.FindControl("txtWed");
                txtTue = (TextBox)e.Row.FindControl("txtTue");
                txtThur = (TextBox)e.Row.FindControl("txtThur");
                txtFri = (TextBox)e.Row.FindControl("txtFri");
                txtSat = (TextBox)e.Row.FindControl("txtSat");
                txtSun = (TextBox)e.Row.FindControl("txtSun");
                totalAll = (TextBox)e.Row.FindControl("txtTotalAll");
                
                    txtMon.Attributes.Add("onBlur", "JvfunonBlur('" + txtMon.ClientID + "','" + txtTue.ClientID + "', '" + txtWed.ClientID + "', '" + txtThur.ClientID + "', '" + txtFri.ClientID + "', '" + txtSat.ClientID + "', '" + txtSun.ClientID + "' , '" + total.ClientID + "');");
                    txtTue.Attributes.Add("onBlur", "JvfunonBlur('" + txtMon.ClientID + "','" + txtTue.ClientID + "', '" + txtWed.ClientID + "', '" + txtThur.ClientID + "', '" + txtFri.ClientID + "', '" + txtSat.ClientID + "', '" + txtSun.ClientID + "', '" + total.ClientID + "');");
                    txtWed.Attributes.Add("onBlur", "JvfunonBlur('" + txtMon.ClientID + "', '" + txtTue.ClientID + "', '" + txtWed.ClientID + "', '" + txtThur.ClientID + "', '" + txtFri.ClientID + "', '" + txtSat.ClientID + "', '" + txtSun.ClientID + "', '" + total.ClientID + "');");
                    txtThur.Attributes.Add("onBlur", "JvfunonBlur('" + txtMon.ClientID + "','" + txtTue.ClientID + "', '" + txtWed.ClientID + "', '" + txtThur.ClientID + "', '" + txtFri.ClientID + "', '" + txtSat.ClientID + "', '" + txtSun.ClientID + "', '" + total.ClientID + "');");
                    txtFri.Attributes.Add("onBlur", "JvfunonBlur('" + txtMon.ClientID + "','" + txtTue.ClientID + "', '" + txtWed.ClientID + "', '" + txtThur.ClientID + "', '" + txtFri.ClientID + "', '" + txtSat.ClientID + "', '" + txtSun.ClientID + "', '" + total.ClientID + "');");
                    txtSat.Attributes.Add("onBlur", "JvfunonBlur('" + txtMon.ClientID + "','" + txtTue.ClientID + "', '" + txtWed.ClientID + "', '" + txtThur.ClientID + "', '" + txtFri.ClientID + "', '" + txtSat.ClientID + "', '" + txtSun.ClientID + "', '" + total.ClientID + "');");
                    txtSun.Attributes.Add("onBlur", "JvfunonBlur('" + txtMon.ClientID + "','" + txtTue.ClientID + "', '" + txtWed.ClientID + "', '" + txtThur.ClientID + "', '" + txtFri.ClientID + "', '" + txtSat.ClientID + "', '" + txtSun.ClientID + "' , '" + total.ClientID + "');");
                    total.Attributes.Add("onBlur", "JvfunonBlur('" + txtMon.ClientID + "','" + txtTue.ClientID + "', '" + txtWed.ClientID + "', '" + txtThur.ClientID + "', '" + txtFri.ClientID + "', '" + txtSat.ClientID + "', '" + txtSun.ClientID + "' , '" + total.ClientID + "');");
                    //totalAll.Attributes.Add("onBlur", "JvfunonBlur('" + total.ClientID + "');");
            }
 
        }

        public static bool IsOdd(int value)
        {
            return value % 2 != 0;
        }
        protected void btnSubmit_Click1(object sender, EventArgs e)
        {
            String userName = Session["User"].ToString();

            //Check to See if this friday is a payRoll Date.
            bool isOddNum = false;
            ArrayList evenFridays = new ArrayList();

             Hashtable allFridays = new Hashtable();
          allFridays = GetAllFridaysInAGivingYear(System.DateTime.Now.Year);
          
          if (allFridays.ContainsKey(Session["dateOfGivingFriday"]))
          {
              //Get the value of this Friday. If even number then it is a payroll day.
              String val;
              val = allFridays[Session["dateOfGivingFriday"]].ToString();
              //Check if the value is Odd. If Odd then this friday is a payday.
              isOddNum = IsOdd(int.Parse(val));
          }
       
            //Loop through all rows of the grid view and get the values of the text boxes.
          
                    TextBox sun, mon, tue, wed, thur, fri, sat, rowTotal;
                    DropDownList project;
                    FinalHoursList fHoursList = new FinalHoursList();
                    int tSun = 0, tMon = 0, tTue = 0, tWed = 0, tThur = 0, tFri = 0, tSat = 0;
                    for (int i = 0; i < 12; i++)
                    {
                        project = (DropDownList)gdvTimeBooking.Rows[i].FindControl("ddlProject");
                        if (project.SelectedIndex != 0)
                        {
                            Hours hour = new Hours();
                            MembershipUser m_User = Membership.GetUser(userName);
                            hour.UserId = m_User.ProviderUserKey.ToString();
                            sun = (TextBox)gdvTimeBooking.Rows[i].FindControl("txtSun");
                            mon = (TextBox)gdvTimeBooking.Rows[i].FindControl("txtMon");
                            tue = (TextBox)gdvTimeBooking.Rows[i].FindControl("txtTue");
                            wed = (TextBox)gdvTimeBooking.Rows[i].FindControl("txtWed");
                            thur = (TextBox)gdvTimeBooking.Rows[i].FindControl("txtThur");
                            fri = (TextBox)gdvTimeBooking.Rows[i].FindControl("txtFri");
                            sat = (TextBox)gdvTimeBooking.Rows[i].FindControl("txtSat");
                            rowTotal = (TextBox)gdvTimeBooking.Rows[i].FindControl("txtTotal");
                            hour.ProjectId = project.SelectedValue;
                            if ( DBNull.Value.Equals( gdvTimeBooking.DataKeys[gdvTimeBooking.Rows[i].RowIndex].Values["Id"]))
                            {
                                hour.UpdateOrCreate = "Create";
                            }
                            else
                            {
                                hour.TimeSheetId = gdvTimeBooking.DataKeys[gdvTimeBooking.Rows[i].RowIndex].Values["Id"].ToString();
                                hour.UpdateOrCreate = "Update";
                            }
                            hour.WeekStartDate = gdvTimeBooking.HeaderRow.Cells[1].Text;
                            hour.WeekStartDate = hour.WeekStartDate.Replace("Saturday<br/>", " ");
                            hour.WeekStartDate = hour.WeekStartDate.TrimStart();
                            String yearNo;
                            if (gdvTimeBooking.DataKeys[gdvTimeBooking.Rows[i].RowIndex].Values["Year"].ToString() == "")
                            {
                                yearNo = System.DateTime.Now.Year.ToString();
                            }
                            else
                            {
                                yearNo = gdvTimeBooking.DataKeys[gdvTimeBooking.Rows[i].RowIndex].Values["Year"].ToString();
                            }
                            hour.WeekStartDate = hour.WeekStartDate + "-" + yearNo;
                            if (rowTotal.Text != "")
                            {
                                hour.RowTotal = rowTotal.Text;
                            }
                            if (sun.Text != "")
                            {
                                hour.Sun = sun.Text;
                            }
                            if (mon.Text != "")
                            {
                                hour.Mon = mon.Text;
                            }
                            if (tue.Text != "")
                            {
                                hour.Tue = tue.Text;
                            }
                            if (wed.Text != "")
                            {
                                hour.Wed = wed.Text;
                            }
                            if (thur.Text != "")
                            {
                                hour.Thur = thur.Text;
                            }
                            if (fri.Text != "")
                            {
                                hour.Fri = fri.Text;
                            }
                            if (sat.Text != "")
                            {
                                hour.Sat = sat.Text;
                            }
                            if (!isOddNum)
                            {
                                hour.IsPayRoll = "True";
                            }
                            else
                            {
                                hour.IsPayRoll = "False";
                            }
                            hour.Year = System.DateTime.Now.Year.ToString();
                            //Get the Week Number.
                            DateTime dateToday = DateTime.Now;
                            int weekNo;
                            weekNo = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(dateToday, CalendarWeekRule.FirstFullWeek, DayOfWeek.Saturday);
                            hour.WeekNo = weekNo.ToString();
                            hour.Year = dateToday.Year.ToString();
                            fHoursList.FinalHours.Add(hour);

                        }
}
                    DAL dal = new DAL();
                    bool retval = false;
                    foreach (Hours hour in fHoursList.FinalHours)
                    {
                        if (hour.UpdateOrCreate.Equals("Update"))
                        {
                            retval = dal.UpdateTimeSheet(hour);
                            if (retval)
                                btnSubmit.Text = "Update";
                        }
                        else if(hour.UpdateOrCreate.Equals("Create") )
                        {
                            retval = dal.CreateTimeSheet(hour);
                            if (retval)
                                  btnSubmit.Text = "Update";
                        }
                        
                    }
                //Reload the grid.
                    Page_Load(sender, e);
               
        }
        
        static DateTime LastDayOfWeek(int year, int weekNum)
        {
         
            DateTime jan1 = new DateTime(year, 1, 1);
            int daysOffset = DayOfWeek.Friday - jan1.DayOfWeek;
            DateTime friday = jan1.AddDays(daysOffset);
            
            var cal = CultureInfo.CurrentCulture.Calendar;
            int firstWeek = cal.GetWeekOfYear(friday, CalendarWeekRule.FirstFullWeek, DayOfWeek.Saturday);

            if (firstWeek <= 1)
            {
                weekNum -= 1;
            }

            DateTime result = friday.AddDays(weekNum * 7);
            return result;
        }



        static Hashtable GetAllFridaysInAGivingYear(int year)
        {
            int counter = 0;
            DateTime result = DateTime.Now;
            Hashtable fridays = new Hashtable();
            for (int i = 0; i < 52; i++)
            {
                counter = i;
               
                DateTime jan1 = new DateTime(year, 1, 1);
                int daysOffset = DayOfWeek.Friday - jan1.DayOfWeek;
                DateTime firstSat = jan1.AddDays(daysOffset);

                var cal = CultureInfo.CurrentCulture.Calendar;
                int firstWeek = cal.GetWeekOfYear(firstSat, CalendarWeekRule.FirstFullWeek, DayOfWeek.Saturday);

                if (firstWeek <= 1)
                {
                    i -= 1;
                    result = firstSat.AddDays(i * 7);
                    counter += 1;
                    fridays.Add(result.ToString("MM-dd"), counter);
                    i++;
                }
                else
                {
                    result = firstSat.AddDays(i * 7);
                    counter += 1;
                    fridays.Add(result.ToString("MM-dd-yyyy"), counter);
                }
            }
            return fridays;
        }
        private void GetDaysFromWeekNo()
        {
            int weekNo = 39;
            DateTime myBaseDate = new DateTime(2014, 1, 1);
            DateTime startDate, endDate;
            myBaseDate = myBaseDate.AddDays(weekNo * 7);

        }
    }
    //private System.Collections.Specialized.NameValueCollection GetNextDate()
    //{
    //    System.Collections.Specialized.NameValueCollection days = new System.Collections.Specialized.NameValueCollection();
    //    DateTime now = DateTime.Today;
    //    int today = (int)now.DayOfWeek;
    //    int[] nextDay = {-1, 0, 1, 2, 3, 4, 5};
    //    days = GetNextDates(nextDay, now.DayOfWeek);


    //    return days;
    //}
    //private System.Collections.Specialized.NameValueCollection GetNextDates(int[] nDays, System.DayOfWeek today)
    //{
    //    Hashtable days = new Hashtable();
    //    System.Collections.Specialized.NameValueCollection li = new System.Collections.Specialized.NameValueCollection();
    //    for (int i = 0; i < nDays.Length; i++)
    //    {
    //        int find = nDays[i];
    //        int delta = find - (int)today;
    //        DateTime da;
    //        da = DateTime.Now.AddDays(delta);
    //        li.Add(DateTime.Now.AddDays(delta).DayOfWeek.ToString(), DateTime.Now.AddDays(delta).ToString());
    //    }
    //    return li;
    //}
}
